<template>
  <my-container>
    <el-form
      class="ad-form-query"
      :inline="true"
      :model="filter"
      @submit.native.prevent
    >
      <el-form-item
        label="物料类型"
        prop="xbctypeid"
      >
        <el-select
          v-model="filter.wllb"
          filterable
          placeholder="请选择物料类型"
          style="width: 100%;"
          @change="changeValue"
        >
          <el-option
            v-for="item in xbsTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="checkPermission(['api:warehouse:stockout:getkcpage'])">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="ckEvent()"
        >出库</el-button>
      </el-form-item>
    </el-form>

    <!-- <vxe-toolbar>
      <template v-slot:buttons>
        <vxe-button @click="insertEvent()">新增</vxe-button>
      </template>:keep-source="true"    keep-source    :auto-resize="true"
    </vxe-toolbar> :sync-resize="filter.wllb"  -->

    <vxe-modal
      id="edit"
      v-model="ckShow"
      resize
      :destroy-on-close="true"
      remember
      fullscreen
    >
      <template v-slot:title>
        <span>出库:{{ getSelectLabel(filter.wllb, 'value', 'label', xbsTypeList) }}</span>
      </template>
      <vxe-toolbar perfect>
        <template v-slot:buttons>
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="insertEvent()"
          >出库</el-button>
          <el-button
            type="primary"
            icon="el-icon-check"
            @click="saveEvent()"
          >保存</el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh-left"
            @click="getStockOutListPage()"
          >刷新</el-button>
        </template>
      </vxe-toolbar>

      <template>
        <vxe-table
          ref="xxTable"
          :loading="loading"
          border
          :keep-source="true"
          :auto-resize="true"
          size="small"
          stripe
          resizable
          :edit-rules="validRules"
          :data="tableData"
          :edit-config="{
            trigger: 'click',
            mode: 'row',
            activeMethod: activeRowMethod
          }"
          @edit-actived="editActivedEvent"
        >
          <vxe-table-column
            type="seq"
            width="60"
          />
          <vxe-table-column
            field="stockInId"
            :visible="false"
          />
          <vxe-table-column
            field="outStorageBatchCode"
            title="出库批次"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="addStorageBatchCode"
            title="入库批次"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="conf.isProduceNumb"
            field="materialCode"
            title="物料编码"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="wlCode"
            title="物料号"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="wlms"
            title="物料描述"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="wlgg"
            title="物料规格"
            show-overflow
            :edit-render="{ name: 'ElInput', props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="dw"
            title="单位"
            :edit-render="{ name: 'ElInput',props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="xbcLocationCode"
            title="库位"
            :edit-render="{ name: 'ElInput',props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="!conf.isSingle"
            field="num"
            title="出库数量"
            :edit-render="{ name: 'ElInputNumber',props: { min: 0} }"
          />
          <vxe-table-column
            v-if="conf.isRegProduBatch"
            field="productBatchCode"
            title="生产批号"
            :edit-render="{ name: 'ElInput' }"
          />
          <vxe-table-column
            v-if="conf.isRegLlBatch"
            field="materialBatchCode"
            show-overflow
            title="来料批次"
            :edit-render="{ name: 'ElInput',props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="conf.isTerm"
            field="effectiveDate"
            title="有效期"
            :edit-render="{ name: 'ElDatePicker', props: { type: 'date',disabled: editDisabled } }"
          />
          <vxe-table-column
            field="outStorageDate"
            title="出库时间"
            show-overflow
            :edit-render="{ name: 'ElDatePicker', props: { type: 'datetime' , format: 'yyyy-MM-dd HH:mm:ss',disabled: editDisabled } }"
          />
          <vxe-table-column
            v-if="conf.isRegEquip"
            field="machineId"
            title="设备号"
            :edit-render="{ name: 'ElInput',props: { disabled: editDisabled } }"
          />
          <vxe-table-column
            field="remark"
            title="备注"
            :edit-render="{ name: 'ElInput' }"
          />
        </vxe-table>
        <vxe-pager
          perfect
          :current-page.sync="tablePage.currentPage"
          :page-size.sync="tablePage.pageSize"
          :total="tablePage.total"
          :layouts="[
            'PrevJump',
            'PrevPage',
            'Number',
            'NextPage',
            'NextJump',
            'Sizes',
            'FullJump',
            'Total'
          ]"
          @page-change="pageChangeEvent"
        />
      </template>
    </vxe-modal>
    <vxe-modal id="ssss" v-model="modalShow" width="1100" height="670" min-width="460" min-height="320">
      <template v-slot:title>
        <span>挑选库存物料</span>
      </template>
      <template>
        <el-form class="ad-form-query" :inline="true" :model="mfilter" @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="mfilter.wlCode"
              placeholder="物料号"
              clearable
              @keyup.enter.native="getStockInListPage"
            >
              <template #prefix>
                <i class="el-input__icon el-icon-search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" type="primary" @click="getStockInListPage">刷新</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-plus" type="primary" @click="confirmselection">确认</el-button>
            <!-- @click="onAdd"     :sync-resize="filter.wllb"-->
          </el-form-item>
        </el-form>

        <vxe-grid
          border
          resizable
          stripe
          :auto-resize="true"
          show-overflow
          size="small"
          height="500"
          :sync-resize="modalShow"
          :loading="mloading"
          :seq-config="{startIndex: (mtablePage.currentPage - 1) * mtablePage.pageSize}"
          :pager-config="mtablePage"
          :columns="mtableColumn"
          :data="mtableData"
          @page-change="handlePageChange"
          @checkbox-change="checkboxchange"
        />
      </template>
      <!-- :sync-resize="value11"
          :pager-config="tablePage"
          :proxy-config="tableProxy"
          :columns="tableColumn"
          :toolbar="tableToolbar" -->
    </vxe-modal>
    <template #footer />
  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { getxbcTypeList, getXbcTypeConf } from '@/api/warehouse/xbctype'
import { getMaterInfo } from '@/api/warehouse/stockin'
import { getStockOutListPage, getStockInkcListPage, addStockOut } from '@/api/warehouse/stockout'
import MyContainer from '@/components/my-container'
export default {
  name: 'Stockout',
  components: { MyContainer },
  data() {
    return {
      modalShow: false,
      ckShow: false,
      mheight: 500,
      theight: this.mheight - 50,
      conf: {
        isTerm: false, // 是否有效期
        isRegLlBatch: false, // 是否记录来料批次
        isSingle: false, // 是否单个入库
        isProduceNumb: false, // 是否生成编号
        prefix: '', // 编号前缀
        canReturn: false, // 是否要归还
        isThawWare: false, // 是否有解冻仓库
        isRegEquip: false, // 出库是否记录设备号
        isRegProduBatch: false, // 是否记录产品批号
        isRegMaterArriDate: false, // 是否记录来料日期
        isRegPcbLot: false, // 是否等级pcblot号
        showCustomCode: false // 是否显示客户代码
      },
      records: [],
      mloading: false, // 模态窗口的加载
      loading: false,
      xbsTypeList: [], // 物料下拉
      filter: {
        wllb: '' // 物料类别
      },
      mfilter: {
        wllb: '', // 物料类别
        wlCode: ''// 物料号
      },
      mwllb: '', // 模态窗口的物料类别
      editDisabled: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      mtablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      validRules: {

      },
      tableData: [],
      ptypeList: [],
      locationList: [],
      cachePnameList: [],
      mtableColumn: [],
      mtableData: []
    }
  },
  mounted() {
    this.getxbcTypeList()
  },
  created() { },
  methods: {
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    insertEvent() {
      // console.log('wl', this.filter.wllb)
      if (this.filter.wllb !== null && this.filter.wllb !== '') {
        this.records = []
        this.mtableColumn = [
          { type: 'checkbox', width: 50 },
          // { type: 'seq', width: 60 },
          { field: 'stockInId', title: '入库id', width: 110, visible: false },
          { field: 'materialCode', title: '物料编码', width: 110, visible: this.conf.isProduceNumb },
          { field: 'customerCode', title: '客户代码', width: 80, visible: this.conf.showCustomCode },
          { field: 'addStorageBatchCode', title: '入库批次', width: 110 },
          { field: 'wlCode', title: '物料号', width: 130 },
          { field: 'wlms', title: '物料名称', width: 130 },
          { field: 'wlgg', title: '物料规格', width: 150 },
          { field: 'xbcLocationCode', title: '库位', width: 90 },
          // { field: 'productBatchCode', title: '产品批号', width: 110, visible: this.conf.isRegProduBatch },
          { field: 'materialBatchCode', title: '来料批次', width: 170, visible: this.conf.isRegLlBatch },
          { field: 'materArriDate', title: '来料日期', width: 120, formatter: this.formatDate, visible: this.conf.isRegMaterArriDate },
          { field: 'remainNum', title: '库存数量', width: 110, visible: !this.conf.isSingle },
          { field: 'dw', title: '单位', width: 80 },
          { field: 'effectiveDate', title: '有效期', width: 110, formatter: this.formatDate, visible: this.conf.isTerm },
          { field: 'remark', title: '备注', width: 120 }
        ]
        // if (this.mfilter.wllb !== this.filter.wllb) {
        this.mtablePage = {
          total: 0,
          currentPage: 1,
          pageSize: 10
        }
        this.mfilter.wllb = this.filter.wllb
        this.mfilter.wlCode = ''
        this.modalShow = !this.modalShow
        this.getStockInListPage()
        // }
      } else {
        this.$XModal.message({ status: 'warning', message: '请选择物料类别！' })
      }
    //   var record = {}
    //   this.$refs.xTable.insert(record)
    },
    getSelectLabel(value, valueProp, labelProp, list) {
      const item = XEUtils.find(list, item => item[valueProp] === value)
      return item ? item[labelProp] : null
    },
    async handlePageChange({ currentPage, pageSize }) {
      this.mtablePage.currentPage = currentPage
      this.mtablePage.pageSize = pageSize
      await this.getStockInListPage()
    },
    // 弹出框加载数据
    async getStockInListPage() {
      const para = {
        currentPage: this.mtablePage.currentPage,
        pageSize: this.mtablePage.pageSize,
        filter: this.mfilter
      }
      this.mloading = true
      const res = await getStockInkcListPage(para)
      this.mloading = false

      if (!res?.success) {
        return
      }

      this.mtablePage.total = res.data.total
      const data = res.data.list
      this.mtableData = data
    },

    async getStockOutListPage() {
      const para = {
        currentPage: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize,
        filter: this.filter
      }
      this.loading = true
      const res = await getStockOutListPage(para)
      this.loading = false

      if (!res?.success) {
        return
      }

      this.tablePage.total = res.data.total
      const data = res.data.list
      this.tableData = data
    },
    async loadData() {
      await this.getStockOutListPage()
    },
    async ckEvent() {
      if (this.filter.wllb === '') {
        this.$XModal.message({ status: 'warning', message: '请选择物料类型！' })
      } else {
        this.ckShow = !this.ckShow
        this.validRules = { xbcMatterrialId: [
          { required: true, message: '物料号不可为空' }
        ],
        xbcLocationId: [
          { required: true, message: '库位不可为空' }
        ] }
        if (this.conf.isRegProduBatch) {
          this.$set(this.validRules, 'productBatchCode', [{ required: true, message: '生产批号不可为空' }])
        }

        const res2 = await getXbcTypeConf({ id: this.filter.wllb })
        if (res2 && res2.success) {
          this.conf = res2.data
        }
        await this.loadData()
      }
    },
    async changeValue() {
      // this.validRules = { xbcMatterrialId: [
      //   { required: true, message: '物料号不可为空' }
      // ],
      // xbcLocationId: [
      //   { required: true, message: '库位不可为空' }
      // ] }
      // if (this.conf.isRegProduBatch) {
      //   this.$set(this.validRules, 'productBatchCode', [{ required: true, message: '生产批号不可为空' }])
      // }

      // const res2 = await getXbcTypeConf({ id: this.filter.wllb })
      // if (res2 && res2.success) {
      //   this.conf = res2.data
      // }
      // await this.loadData()
    },
    checkboxchange(event) {
      this.records = event.records
      // console.log('records', this.records)
    },
    confirmselection() {
      this.modalShow = !this.modalShow
      this.records.map((x) => {
        var record = {
          'stockInId': x.stockInId,
          'addStorageBatchCode': x.addStorageBatchCode,
          'materialCode': x.materialCode,
          'wlCode': x.wlCode,
          'wlms': x.wlms,
          'wlgg': x.wlgg,
          'dw': x.dw,
          'xbcLocationCode': x.xbcLocationCode,
          'materialBatchCode': x.materialBatchCode,
          'effectiveDate': x.effectiveDate
        }
        this.$refs.xxTable.insert(record)
      })

      // this.$XModal.confirm('您确定要删除吗？').then(type => {
      //   this.$XModal.message({ message: `点击了 ${type}` })
      // })
    },
    activeRowMethod({ row, rowIndex }) {
      return row.outStorageBatchCode === null
    },
    editActivedEvent({ rowIndex, row }) {
      this.editDisabled = row.outStorageBatchCode === null
    },
    async getxbcTypeList() {
      const res = await getxbcTypeList()
      if (res && res.success) {
        this.xbsTypeList = res.data
      }
    },
    // 格式化显示名称
    formatPanmeLabel({ cellValue, row }) {
      var ptype = row.attr3
      var ptypeItem = this.cachePnameList.find(item => item.ptype === ptype)
      if (ptypeItem && ptypeItem.pnameList) {
        var pnameItem = ptypeItem.pnameList.find(
          item => item.value === cellValue
        )
        if (pnameItem) {
          return pnameItem.label
        }
      }
      return ''
    },
    async saveEvent() {
      const errMap = await this.$refs.xxTable.validate().catch(errMap => errMap)
      if (errMap) {
        this.$XModal.message({ status: 'error', message: '校验不通过！' })
      } else {
        const {
          insertRecords,
          // eslint-disable-next-line no-unused-vars
          removeRecords,
          // eslint-disable-next-line no-unused-vars
          updateRecords
        } = this.$refs.xxTable.getRecordset()

        if (insertRecords.length !== 0) {
          var st = await addStockOut(insertRecords)
          console.log(st)
          if (st.success === false) {
            //  this.$XModal.message({ status: 'error', message: st.msg })
          } else {
            this.$message({
              message: '出库成功！',
              type: 'success'
            })
          }

          // 刷新
          await this.getStockOutListPage()
        } else {
          this.$XModal.message({ status: 'warning', message: '没有新增数据！' })
        }
      // this.$XModal.alert(insertRecords)
      }
    },
    async pageChangeEvent() {
      await this.getStockOutListPage()
    },
    // 更新级联选项列表
    updatePnameList(row) {
      var ptype = row.attr3
      var pnameList = []
      if (ptype) {
        var item = this.cachePnameList.find(item => item.ptype === ptype)
        if (item) {
          pnameList = item.pnameList
        } else {
          // 模拟后台数据
          Array.from(new Array(XEUtils.random(3, 8))).forEach((item, index) => {
            pnameList.push({
              label: `${ptype}-名称${index}`,
              value: `${ptype}_${index}`
            })
          })
          this.cachePnameList.push({ ptype, pnameList })
        }
      }
      console.log(pnameList)
      // this.pnameList = pnameList
    },
    async ptypeChangeEvent({ row }) {
      // 类型切换时更新级联的下拉数据
      var res = await this.getMaterInfo(row.xbcMatterrialId)
      console.log('res', res)
      if (res && res.success) {
        row.wlms = res.data.wlms
        row.wlgg = res.data.wlgg
        row.dw = res.data.dw
      }
    },
    async getMaterInfo(id) {
      return await getMaterInfo({ id: id })
    }
  }
}
</script>
